package com.boruan.shengtangfeng.admin.jwt.filter;

import java.io.IOException;
import java.util.Date;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.boruan.shengtangfeng.admin.jwt.UserSubject;
import com.boruan.shengtangfeng.admin.jwt.util.JwtUtil;
import com.boruan.shengtangfeng.core.entity.SystemUser;
import com.boruan.shengtangfeng.core.service.ISystemUserService;
import com.boruan.shengtangfeng.core.utils.CookieUtil;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.utils.GlobalReponseResultEnum;
import com.boruan.shengtangfeng.core.vo.LoginResult;
import com.boruan.shengtangfeng.core.vo.SystemUserVo;
import com.boruan.shengtangfeng.core.vo.mapper.SystemUserVoMapper;

/**
 * 验证用户名密码正确后，生成一个token，并将token返回给客户端
 * 该类继承自UsernamePasswordAuthenticationFilter，重写了其中的2个方法 attemptAuthentication
 * ：接收并解析用户凭证。 successfulAuthentication ：用户成功登录后，这个方法会被调用，我们在这个方法里生成token。
 */
@SuppressWarnings("all")
public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {

	private AuthenticationManager authenticationManager;
	@Value("${jwt.header}")
	private String tokenHeader;

	@Value("${jwt.tokenHead}")
	private String tokenHead;

	@Autowired
	private JwtUtil jwtUtil;
	@Autowired
	private ISystemUserService userService;

	public JWTLoginFilter(AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
		super.setAuthenticationManager(authenticationManager);
	}

	// 接收并解析用户凭证
//    @Override
//    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException {
//        try {
//        	JwtUser user = new ObjectMapper().readValue(req.getInputStream(), JwtUser.class);
//            return authenticationManager.authenticate(
//                    new UsernamePasswordAuthenticationToken(
//                            user.getUsername(),
//                            user.getPassword(),
//                            new ArrayList<>())
//            );
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }
	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {
		return super.attemptAuthentication(request, response);
	}

	// 用户成功登录后，这个方法会被调用，我们在这个方法里生成token
	@Override
	protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
			Authentication auth) throws IOException, ServletException {
		// 生成token
		String token = null;
		try {
			UsernamePasswordAuthenticationToken authToken = (UsernamePasswordAuthenticationToken) auth;
			UserSubject jwtUser = (UserSubject) authToken.getPrincipal();
			token = jwtUtil.generateToken(jwtUser.getId(), jwtUser.getLoginName(), jwtUser.getName(), null);
			res.addHeader(tokenHeader, tokenHead + token);
			GlobalReponse globalReponse = new GlobalReponse(GlobalReponseResultEnum.SUCCESS);
			Date expirationDate = jwtUtil.getExpirationDateFromToken(token);
			CookieUtil.writeLoginToken(res, token, -1);
			SystemUser user = userService.findById(jwtUser.getId());
			SystemUserVo userVo = SystemUserVoMapper.MAPPER.toVo(user);
			// userVo.setToken(tokenHead+token);
			LoginResult loginResult = new LoginResult();
			loginResult.setAdmin(userVo);
			loginResult.setToken(tokenHead + token);
			globalReponse.setData(loginResult);
			res.setContentType("application/json;charset=UTF-8");
			SerializeConfig config = new SerializeConfig();
//			config.configEnumAsJavaBean(UserType.class);
//			config.configEnumAsJavaBean(Sex.class);
//			config.configEnumAsJavaBean(UserCheckStatus.class);
			res.getWriter().write(JSON.toJSONString(globalReponse, config));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
